﻿using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.Net.Sockets;
//using System.Net.Security;

namespace Xcap
{
    public delegate void DataRecievedEventHandler(object sender, DataRecievedEventArgs e);

    public class XcapCore
    {
        NetworkStream stream = null;
        TcpClient client = null;
        protected Config config;                                //objekt konfiguracie
        protected Account account;                              //objekt uctu prihlaseneho uzivatela

        public XcapCore(Config _config, Account _account)
        {
            config = _config;
            account = _account;
        }

        /// <summary>
        /// Connects to a server by specified port
        /// </summary>
        public void Connect()
        { 
            //Debug.WriteLine("Connecting...");
            client = new TcpClient();
            client.Connect(config.Host, config.Port);

            stream = client.GetStream();
        }

        /// <summary>
        /// Closes an opened network stream
        /// </summary>
        public void Disconnect()
        {
            //if(client.Connected == true)
                stream.Close();
        }

        /// <summary>
        /// Sends and receives the XCAP request
        /// </summary>
        /// <param name="request"></param>
        /// <returns>Server response</returns>
        protected string Send(string request)
        {
            //Debug.WriteLine("Sending...");
            
            byte[] send = Encoding.ASCII.GetBytes(request);
            stream.Write(send, 0, send.Length);

            //Debug.WriteLine("Recieving...");
            byte[] bytes = new byte[client.ReceiveBufferSize];
            int count = stream.Read(bytes, 0, (int)client.ReceiveBufferSize);
            
            //tu je zmena oproti desctop verzii
            //String data = Encoding.ASCII.GetString(bytes);
            String data = Encoding.ASCII.GetString(bytes,0,count);
            //char[] unused = { (char)data[count] };

            //uzavrieme stream
            //stream.Close();

            return data;//.TrimEnd(unused);
        }

        /// <summary>
        /// Save stream to a log file
        /// TODO: dorobit ulozenie do log.dat suboru
        /// </summary>
        /// <param name="data"></param>
        private void SaveToLog(string data)
        { 
            throw (new NotImplementedException());
        }
    }
}
